import sys
import time 
input("按回车键启动...")

try:
    from selenium import webdriver
    from webdrive import getDriver
    from selenium.webdriver.support.ui import WebDriverWait
    from commonutils import shared_lessons, before_read, ai_assitant, video_list, interrupt_test, finish_flag, play_video, video_area, current_time, accelerate_video
    from selenium.webdriver.common.by import By
except Exception as e:
    print(f"导入模块时发生错误: {e}")
    input("按回车键退出...")
    sys.exit(1)

def get_driver(url):
    print("activating the chrome browser......")
    options = webdriver.ChromeOptions()
    # selenium尝试连接https网站时会报SSL handshake failed, 加上以下两行代码可以忽略证书错误
    options.add_argument('--ignore-certificate-errors')
    # 设置日志级别为3, 仅记录警告和错误
    options.add_argument('--log-level=3')

    driver = webdriver.Chrome(options=options)
    # will block here due to function get() until it jumps to url
    driver.get(url)
    return driver

def autovideo(driver):
    input("确认完成跳转到学生首页后按回车继续...")
    all_lessons = shared_lessons(driver)

    if len(all_lessons) == 0:
        print("没有找到任何课程")
        return

    root_window_handle=driver.current_window_handle

    for name, test in all_lessons:
        print(f"即将进入课程:{name.text}(Y/N)", end=" ")
        choose = input().strip().upper()
        if choose == 'Y' or choose == "YES":
            # 这个是原窗口打开的
            name.click()
            print("正在跳转页面, 限时30s...")
            # 这里超时会异常
            WebDriverWait(driver, 30).until(lambda d: "课程学习" in d.title or "智慧树" in d.title)
            # 默认新窗口句柄追加在列表尾
            driver.switch_to.window(driver.window_handles[-1])
            print("跳转完成...")
            # 学前阅读弹窗检测
            beforeread = before_read(driver)
            close = beforeread
            try:
                close.click()
                print("成功关闭学前阅读弹窗...")
            except Exception as e:
                print(f"关闭弹窗时出错: {e}")
            # ai助手检测（可能会遮挡）
            ai, close = ai_assitant(driver)
            try:
                close.click()
                print("成功关闭ai助手...")
            except Exception as e:
                print(f"关闭ai助手时出错: {e}")
            print('开始获取课程视频列表...')
            all_video = video_list(driver)
            print('开始自动播放课程视频...')
            print('是否自动开启1.5倍速——仍在Beta测试阶段(Y/N)：')
            accelerate_yes = input().strip().upper()
            for video_item in all_video:
                # 快速跳过已播放视频
                if finish_flag(video_item):
                    continue

                first_div = video_item.find_element(By.TAG_NAME, 'div')
                first_span = first_div.find_element(By.TAG_NAME, 'span')
                print(f'播放: {first_span.text}')
                video_item.click()
                print('[Debug] 等待网页稳定5s...')
                # 加速视频
                if accelerate_yes == 'Y' or accelerate_yes == "YES":
                    accelerate_video(driver)
                first_time = current_time(driver)
                first_time = first_time.text
                second_time = ''
                while True:
                    interrupt_test(driver)
                    # 如果是已完成的视频，跳过
                    if finish_flag(video_item):
                        break
                    # 如果视频进度条没动，就播放它
                    second_time = current_time(driver)
                    second_time = second_time.text
                    print(f'[Debug] first_time={first_time} sec_time={second_time}')
                    if first_time == second_time:
                        play_video(driver)
                    first_time = second_time
                    # 睡眠
                    print('[正常] 睡眠开始 10s...')
                    time.sleep(10)
                    print('[正常] 睡眠结束...')

        else:
            continue
    
    print('所有课程视频播放完毕...')
        



def main():
    url = r'https://passport.zhihuishu.com/login?service=https://onlineservice-api.zhihuishu.com/gateway/f/v1/login/gologin'
    
    input("按回车键打开浏览器...")
    driver = getDriver(url)
    input("请登录后按回车继续...")
    autovideo(driver)
    input("请按任意键退出...")
    driver.quit()

if __name__ == '__main__':
    main()

